package com.exam.baidu;

public class Solution {
    private static boolean removeFlag = true;

    public static void main(String[] args) {
        Solution instance = new Solution();
        ListNode head = instance.constructList("123333333217");
        //ListNode head = instance.constructList("12333333321");
        //ListNode head = instance.constructList("123332333341");
        while(removeFlag && head != null && head.next != null) {
            head = instance.removeDuplicates(head);
        }
        String res = instance.parseList(head);
        System.out.println(res);
    }

    public ListNode constructList(String str) {
        if(str == null || str.length() == 0){
            return null;
        }
        ListNode dummy = new ListNode('0');
        int len = str.length();
        ListNode cur = dummy;
        for (int i = 0; i < len; i++) {
            cur.next = new ListNode(str.charAt(i));
            cur = cur.next;
        }
        return dummy.next;
    }

    public String parseList(ListNode head) {
        StringBuilder sb = new StringBuilder();
        ListNode cur = head;
        while(cur != null) {
            sb.append(cur.val);
            cur = cur.next;
        }
        return sb.toString();
    }

    public ListNode removeDuplicates(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        removeFlag = false;
        ListNode dummy = new ListNode('0');
        dummy.next = head;
        ListNode cur = dummy;
        while(cur.next != null && cur.next.next != null){
            if(cur.next.val == cur.next.next.val){
                removeFlag = true;
                char remove = cur.next.val;
                while(cur.next != null && cur.next.val == remove){
                    cur.next = cur.next.next;
                }
            }else{
                cur = cur.next;
            }
        }
        return dummy.next;
    }
}

class ListNode {
    char val;
    ListNode next;
    ListNode() {}
    ListNode(char val) { this.val = val; }
    ListNode(char val, ListNode next) { this.val = val; this.next = next; }
}

